package com.tinyengine.it.service.endpoint;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tinyengine.it.common.utils.JavaDataType;
import com.tinyengine.it.model.entity.DbLogicalFieldsInfo;
import com.tinyengine.it.service.db.DbLogicalFieldsInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommonService {

    @Resource
    private DbLogicalFieldsInfoService dbLogicalFieldsInfoService;

    /**
     * @Description: 组装vo  预定义响应
     * @Author: Ping.Liu
     * @Date: 2025-03-21 - 19:31
     */
    public void processFields(Integer voId, MapBuilder<String, Object> mapBuilder) {
        List<DbLogicalFieldsInfo> fieldsInfos = dbLogicalFieldsInfoService.list(Wrappers.<DbLogicalFieldsInfo>lambdaQuery().eq(DbLogicalFieldsInfo::getTableId, voId));

        for (DbLogicalFieldsInfo fieldsInfo : fieldsInfos) {
            String code = fieldsInfo.getCode();
            String dataType = fieldsInfo.getDataType();

            // vo将被放置在 RequestBody 该文件类型 @RequestBody 不能解析二进制数据  ；
            if (StrUtil.isBlank(dataType) || JavaDataType.File.getValue().equalsIgnoreCase(dataType)  || JavaDataType.Blob.getValue().equalsIgnoreCase(dataType)) {
                continue;
            }
            if (JavaDataType.Object.getValue().equalsIgnoreCase(dataType.toUpperCase())) {
                //创建一个新的 MapBuilder 作为子对象
                MapBuilder<String, Object> childMapBuilder = MapUtil.builder();
                //递归处理子对象的字段
                Integer shipVoId = fieldsInfo.getShipVoId();
                processFields(shipVoId, childMapBuilder);
                //将子 MapBuilder 放入当前 mapBuilder
                mapBuilder.put(code, childMapBuilder.build());
            } else if (JavaDataType.List_Object.getValue().equalsIgnoreCase(dataType.toUpperCase())) {
                //创建一个 List 来存储子对象
                List<Map<String, Object>> list = new ArrayList<>();
                //  创建一个新的 MapBuilder 作为子对象
                MapBuilder<String, Object> childMapBuilder = MapUtil.builder();
                //递归处理子对象的字段
                Integer shipVoId = fieldsInfo.getShipVoId();
                processFields(shipVoId, childMapBuilder);
                //将子 MapBuilder 放入 List
                list.add(childMapBuilder.build());
                //将 List 放入当前 mapBuilder
                mapBuilder.put(code, list);
            } else {
                mapBuilder.put(code, dataType);
            }
        }
    }

}
